package service

import "fmt"

type Category struct {
   ID           int    `json:"id" db:"id"`
   CategoryName    string  `json:"category_name" db:"category_name" binding:"required,max=16"`
}

type Categories struct {
    Items   []Category  `json:"items"`
    Total   int         `json:"total"`
}
func (c Category) Create() (Category, error) {
   r, e := db.Exec("insert into blog_category (category_name) values (?)", c.CategoryName)
   if e != nil {
       return Category{}, e
   }
   id,_ := r.LastInsertId()
   return Category{int(id), c.CategoryName}, nil
}

func (c *Category) Delete() error {
    _, e := db.Exec("delete from blog_category where id=?", c.ID)
    return e
}

func (c *Category) Edit() error  {
    _, e := db.Exec("update blog_category set category_name=? where id=?", c.CategoryName, c.ID)
    return e
}

func (c *Category) GetOne() (Category, error)  {
    var category Category
    e := db.Get(&category, "select * from blog_category where id=?", c.ID)
    return category,e
}

func (c Category) GetAll() (data Categories, err error)  {

    categories := make([]Category, 0)
    if err = db.Select(&categories, "select * from blog_category"); err != nil {
        return
    }

    var total int
    _ = db.Get(&total, "select count(*) from blog_category")
    fmt.Println(total)

    data.Items = categories
    data.Total = total
    return
}
